package com.qf.springmvc02.interceptor;

import com.qf.springmvc02.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @author nk
 * @date 2022/5/5 11:05
 */
public class MyInterceptor implements HandlerInterceptor {

    //preHandle是在处理器Handler执行之前执行的   返回true让请求继续执行，如果返回false 后续拦截器和处理器不执行，直接返回
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //System.out.println("preHandle 执行。。。");
        //登录权限验证的拦截1、从session中取出来的登录用户，判断用户是否登录过，然后决定是拦截或方形
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (Objects.isNull(user)){
            //说明没有登录过，拦截，返回到登录界面
            request.setAttribute("error","用户名或密码错误");
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        }
        //如果登录过的，就放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("post handler....");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion 请求结束了");
    }
}
